import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewScreen extends StatefulWidget {
  final String url;
  final VoidCallback onComplete;

  const WebViewScreen({
    super.key,
    required this.url,
    required this.onComplete,
  });

  @override
  State<WebViewScreen> createState() => _WebViewScreenState();
}

class _WebViewScreenState extends State<WebViewScreen> {
  late final WebViewController _controller;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            setState(() {
              _isLoading = true;
            });
          },
          onPageFinished: (String url) {
            setState(() {
              _isLoading = false;
            });
            // 检查是否完成填写
            _checkCompletion();
          },
          onNavigationRequest: (NavigationRequest request){
            print(request.url);
            return NavigationDecision.navigate;
          }
        ),
      )
      ..loadRequest(Uri.parse(widget.url));
  }

  Future<void> _checkCompletion() async {
    print("现在执行");
    // 通过 JavaScript 检查页面状态
    final result = await _controller.runJavaScriptReturningResult(
      'document.querySelector(".completion-flag") !== null'
    );
    
    if (result == true) {
      widget.onComplete();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('法大大签收单'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () => _controller.reload(),
          ),
        ],
      ),
      body: Stack(
        children: [
          WebViewWidget(controller: _controller),
          // if (_isLoading)
          //   const Center(
          //     child: Column(
          //       mainAxisAlignment: MainAxisAlignment.center,
          //       children:
          //       [CircularProgressIndicator(),
          //       SizedBox(height: 16),
          //       Text("页面加载中")
          //       ]
          //     ),
          //   ),
        ],
      ),
    );
  }
} 